<?php
/**
 * Eren Framework
 * 
 * Define Cache class for File
 * 
 * @category System
 * @author Manu Soros Leu
 * @copyright manusoros@gmail.com
 */

class Eren_Cache_File extends Eren_Cache_Abstract
{   
    /**
     * Init the File Path and File Name by the key 
     * 
     * @param string $key
     * 
     * @return array
     */
    protected function _init($key)
    {
        $ret = array();
        $MD = md5($key);
        $ret['filePath'] = PROJECT_PATH . '/Temp/' . substr($MD, 0, 1) . '/' . substr($MD, 1, 1);
        $ret['fileName'] = $ret['filePath'] . '/' . $MD . '.tmp';
        return $ret;
    }
    
    /**
     * (non-PHPdoc)
     * @see Eren_Cache_Abstract::get()
     */
    public function get($key, $default)
    {
        $file = $this->_init($key);
        if(!file_exists($file['fileName'])){
            return $default;
        }
        $ret = unserialize(Eren_File::readAll($file['fileName']));
        $fileInfo = Eren_File::info($file['fileName']);
        if(time() - $fileInfo['modify'] > $ret['expire']){
            return $default;
        }
        return $ret['value'];
    }
    
    /**
     * (non-PHPdoc)
     * @see Eren_Cache_Abstract::set()
     */
    public function set($key, $value, $expireTime)
    {
        $file = $this->_init($key);
        if(!file_exists($file['filePath'])){
            mkdir($file['filePath'], 0777, TRUE);
        }
        $content['expire'] = $expireTime;
        $content['value'] = $value;
        return Eren_File::write($file['fileName'], serialize($content));
    }
    
    /**
     * (non-PHPdoc)
     * @see Eren_Cache_Abstract::clean()
     */
    public function clean($key)
    {
        $file = $this->_init($key);
        if(!file_exists($file['fileName'])){
            return TRUE;
        }
        return Eren_File::delete($file['fileName']);
    }
}
